﻿using System;
using System.Configuration;
using System.Globalization;
using System.Web;

using BizElements.BusinessLayer;

namespace BizElements.Web
{
    /// <summary>Handles unhandled UI exceptions.</summary>
    public static class ExceptionController
    {
        #region Configuration.

        static ExceptionController()
        {
            string cfgUseCustomErrorPage = ConfigurationManager.AppSettings["BizElements.Web.ExceptionController.UseCustomErrorPage"] ?? ConfigurationManager.AppSettings["Global.UseCustomErrorPage"];
            UseCustomErrorPage = (cfgUseCustomErrorPage == "true");
            SetErrorFormData = ReflectionUtil.TryCreateDelegateFromAppSettings<Delegates.Procedure<Exception>>("BizElements.Web.ExceptionController.SetErrorFormDataAssembly", "BizElements.Web.ExceptionController.SetErrorFormDataClass", "BizElements.Web.ExceptionController.SetErrorFormDataMethod");
            if (!SetErrorFormData.Method.IsStatic)
                throw new InvalidOperationException(string.Format("The method to which SetErrorFormData delegate points must be static. Method '{0}' is not static.", SetErrorFormData.Method.Name));
        }

        /// <summary>Indicates whether custom error page or default ASP.NET error page is used.</summary>
        /// <value>Value configured in <b>BizElements.Web.ExceptionController.UseCustomErrorPage</b> app setting. Default is <b>false</b>.</value>
        public static readonly bool UseCustomErrorPage;

        /// <summary>Error form URL configured in "BizElements.Web.ExceptionController.ErrorFormUrl" appSettings entity in Web.config file.</summary>
        /// <value>Value configured in <b>BizElements.Web.ExceptionController.ErrorFormUrl</b> app setting. Default is <b>"~/Common/ErrorFrm.aspx"</b>.</value>
        public static readonly string ErrorFormUrl = ConfigurationManager.AppSettings["BizElements.Web.ExceptionController.ErrorFormUrl"] ?? "~/Common/ErrorFrm.aspx";

        /// <summary>Sets error form data using static method configured in <b>appSettings</b> section of Web.config file.</summary>
        public static readonly Delegates.Procedure<Exception> SetErrorFormData;

        #endregion

        #region App controller.

        /// <summary>Displays exception in custom error form.</summary>
        public static void RedirectToErrorForm(Exception error)
        {
            if (SetErrorFormData == null)
                throw new InvalidOperationException("SetErrorFormData delegate must be configured in Web.config file. See help file for more details.");

            SetErrorFormData(error);
            HttpContext.Current.Response.Redirect(ErrorFormUrl);
        }

        #endregion
    } 
}
